import { treeType } from '@/types/project';
import { formatCode } from '@/utils/utils';
import { reactive } from 'vue';

/* 源码 */
export const source = reactive({
    /**
     *  false:源码视图
     *  true:代码视图
     *  */
    mode: true,
    /* 代码 */
    code: "",
    /* 源码是否经过翻译 */
    isCompiled: false
})

/* 显示源码，没有经过转换 */
export const showSourceCode = (code: any, tabIndex?: number) => {
    source.isCompiled = false
    source.mode = false
    setCode(code, tabIndex)
}

/* 显示转换后的源码，可直接使用 */
export const showCompiledCode = (code: any, tabIndex?: number) => {
    source.isCompiled = true
    source.mode = false
    setCode(code, tabIndex)
}
// 显示可视化
export const showUI = () => {
    source.mode = true
}


export const setCode = (code: any, tabIndex?: number) => {
    source.code = formatCode(code, tabIndex)
}



export const getCode = () => {
    return source.code
}

/* 递归转换所有属性 */
export const compileCode = (code: string) => {
    var _data = JSON.parse(code);
    function findData(item: treeType): any {
        let config: any = {};
        /* 处理表单类型 */
        if (item.type === 'file') {
            config[item.title] = {
                headers: item.headers,
                values: item.values,
            };
        }

        /* 处理其他类型 */
        item.children.forEach((e) => {
            var res = findData(e);
            if (Object.keys(res).length === 0 && e.type == 'props') {
                config[e.title] = e.value;
            }
            else {
                config[e.title] = res;
            }
        });
        return config;
    }

    var res = findData(_data);

    return formatCode(res);
}

/* 转编单层属性 */
export const compilePropCode = (code: string) => {
    var data = JSON.parse(code)
    return JSON.stringify({
        [data.title]: data.value
    })
}